package com.bipa.controller;

import com.bipa.bean.ArticleType;
import com.bipa.service.ArticleTypeService;
import com.bipa.util.PagerModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ArticleTypeController {
    @Autowired
    ArticleTypeService articleTypeService;

    @RequestMapping("/articleTypeList")
    public ModelAndView toArticleTypeList(@RequestParam(value = "pageIndex",defaultValue = "1")String pageIndex){
        ModelAndView mv = new ModelAndView();
        PagerModel pageModel = new PagerModel();
        //获取页码
        pageModel.setPageIndex(Integer.valueOf(pageIndex));
        pageModel.setTotalNum(articleTypeService.findAll());
        mv.addObject("types",articleTypeService.findLimit(pageModel));
        mv.addObject("pageModel",pageModel);
        mv.addObject("highLight","articleby");
        mv.setViewName("back/articleType_list");
        return mv;
    }

    @RequestMapping("/deleteType")
    public ModelAndView deleteType(@RequestParam("code") String code){
        ModelAndView mv = new ModelAndView();
        articleTypeService.deleteByCode(code);
        mv.addObject("message", "删除成功！");
        mv.setViewName("redirect:./articleTypeList");
        return mv;
    }

    @RequestMapping(value = "/addOrUpdateArticleType",method = RequestMethod.GET)
    public ModelAndView addOrUpdate(@RequestParam(value = "code",defaultValue = "")String code){
        ModelAndView mv = new ModelAndView();
        if (!code.equals("")){
            mv.addObject("articleType",articleTypeService.findByCode(code));
        }
        mv.addObject("types",articleTypeService.findAll1());
        mv.setViewName("back/view");
        return mv;
    }

    @RequestMapping(value = "/addOrUpdateArticleType",method = RequestMethod.POST)
    public ModelAndView addOrUpdate(@ModelAttribute ArticleType articleType){
        ModelAndView mv = new ModelAndView();
        String code = articleType.getCode();
        if (code!=null && !"".equals(code)){
            if(articleTypeService.findByCode(code)!=null){
                articleTypeService.update(articleType);
            }else {
                articleTypeService.insert(articleType);
            }
        }
        mv.setViewName("redirect:./articleTypeList");
        return mv;
    }
}
